package com.lpw.dbvideo.intercepter;

import com.google.gson.Gson;
import com.lpw.dbvideo.utils.JWTUtils;
import com.lpw.dbvideo.utils.JsonData;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginIntercepter implements HandlerInterceptor {

    private static Gson gson = new Gson();

    /**
     * 进入controller 前拦截
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param handler Object
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("token");
        if(token == null){
            token = request.getParameter("token");
        }

        if(token != null){
            Claims claims = JWTUtils.checkJWT(token);
            if(claims != null){
                Integer userId;
                userId = (Integer) claims.get("id");
                String name = (String) claims.get("name");

                request.setAttribute("user_id",userId);
                request.setAttribute("name",name);
                return true;
            }
        }
        sendJsonMessage(response, JsonData.error("请登录"));
        return false;
    }

    /**
     * 响应数据给前端
     * @param response HttpServletResponse
     * @param object Object
     * @throws IOException 异常
     */
    private static void sendJsonMessage(HttpServletResponse response,Object object) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.print(gson.toJson(object));
        printWriter.close();
        response.flushBuffer();
    }
}
